﻿using System;
using System.Web.Helpers;
using System.Web.Mvc;
using Grundy.Administration.Web.Services;
using System.Linq;
using Grundy.Entity;
using Grundy.Common;

namespace Grundy.Administration.Web.Controllers
{
    [Authorize]
    public class FeatureController : Controller
    {
        private FeatureService _featureService;

        public FeatureController()
        {
            _featureService = new FeatureService();
        }

        public FeatureController(FeatureService featureService)
        {
            _featureService = featureService;
        }

        [HttpPost]
        public ActionResult GetFeaturesData(int page = 1, int rows = 0)
        {
            var totalRecords = _featureService.GetFeatures().Count();
            var features = _featureService.GetFeatures(page, rows)
                           .Select(i => new {i.Id, i.Name})
                           .ToList();
            
            var data = new
            {
                total = page,
                page = page,
                records = totalRecords,
                rows = features.Select((i) => new {Id = i.Id, cell = new object[] {i.Id, i.Name}}).ToList()
            };

            return Json(data);
        }

        public ActionResult GetFeatures()
        {
            var totalRecords = _featureService.GetFeatures().Count();
            ViewBag.IsEmpty = totalRecords == 0;
            return View();
        }

        [HttpPost]
        public ActionResult New(string name)
        {
            var feature = _featureService.GetFeature(name);
            if (feature == null)
            {
                var created = _featureService.CreateFeature(name.Trim());
                return Json(new object[]{true, string.Empty, created.Id});
            }
            return Json(new object[]{false, "A feature with the same name already exists.", Guid.Empty});
        }

        public ActionResult SearchFeatures(string term)
        {
            var terms = (term ?? string.Empty).Split(new[] {','}).Select(i => i.Trim()).ToList();
            var toSearch = terms.Last();
            if(toSearch.IsNullOrEmpty() || toSearch.Length < 2)
                return Json(new object[] {}, JsonRequestBehavior.AllowGet);
            
            var matching = _featureService.GetFeatures().Where(i => i.Name.StartsWith(toSearch))
                           .Select(i => i.Name)
                           .ToList()
                           .Where(i => !terms.ContainsIgnoreCase(i));
            return Json(matching, JsonRequestBehavior.AllowGet);
        }
    }
}